版本:laravel 9
摘要
修改 database\migrations\2014_10_12_000000_create_users_table.php
增加一欄
$table->boolean('is_admin')->nullable();
修改 database\seeders\DatabaseSeeder.php
public function run()
{
\App\Models\User::factory()->create([
'name' => 'Administrator',
'email' => 'admin@example.com',
'password' => bcrypt('123456'),
'is_admin' => '1',
]);
}
修改 app\Models\User.php
protected $fillable = [
...
'is_admin'
];
建立 middleware
php artisan make:middleware IsAdmin
app\Http\Middleware\IsAdmin.php
public function handle(Request $request, Closure $next)
{
//return $next($request);
if(auth()->user()->is_admin == 1){
return $next($request);
}
return redirect('home')->with('error',"Only admin can access!");
}
修改 app/Http/Kernel.php
protected $routeMiddleware = [
...
'is_admin' => \App\Http\Middleware\IsAdmin::class,
];
建立 DashboardController
後台首頁通常叫做 dashboard
php make:controller Admin
public function index()
{
return view('admin.dashboard');
}
修改 routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\Admin\DashboardController;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::group(['prefix' => 'admin', 'middleware' => 'is_admin'], function () {
Route::get('/', [DashboardController::class, 'index'])->name('admin.dashboard');
// other admin routes...
});
建立 views/admin/_layouts/app.blade.php
內容複製 views/layouts/app.blade.php
建立 views/admin/dashboard.blade.php
內容複製 views/home.blade.php
是否修改 app/Http/Controllers/Auth/LoginController.php ?
網路上有的做法會重寫 login(),如果 is_admin==1 則導向後台。但我覺得應該不需要。單一登入用的就是前台的登入,既然如此,前台登入就導向前台首頁,合理。若要進入後台,應該是在頁面上提供後台連結。下面供參考。
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required'
]);
$credentials = $request->only('email', 'password');
if(! auth()->attempt($credentials)){
return redirect()->route('login')
->with('error','Email-Address or Password not correct.');
}
if (auth()->user()->is_admin == 1) {
return redirect()->route('admin.dashboard');
}
return redirect()->route('home');
}
參考文章
https://codingdriver.com/laravel-multi-auth-authentication-tutorial-example.html
使用 middleware, IsAdmin
https://www.itsolutionstuff.com/post/laravel-9-multi-auth-create-multiple-authentication-in-laravelexample.html
使用 middleware, UserAccess,可以有不同身份。但是一般來說用不到不同身份,大部份都是拆分前後台,前台user,後台就 admin,然後再設定權限。